<?php
namespace Sfsn\Core\Exception;

use Sfsn\Core\Util\Log;

class Exception extends \Exception
{
    private static $config = [];
    public static function show($e)
    {        
         $config = self::$config;
         $debug = $config['DEBUG']; 
         $errorUrl = $config['ERROR_URL'];
         
         $message = $e->getMessage();        
         $file = '...' . DIRECTORY_SEPARATOR . basename($e->getFile());
         $line = $e->getLine();
         $code = $e->getCode();
        //开启debug显示错误追踪
        if ($config['DEBUG']) {
            //$trace = debug_backtrace();            
            $exceptionTrace = $e->getTrace();
            $trace = self::trace($exceptionTrace);
        }
        
        //记录错误日志        
        $config['LOG_ON'] && Log::write('system', $message);
        
        include SFSN_PATH . 'Core/Tpl/Exception.php';
    }

    public static function trace($trace)
    {
        $path = dirname(SFSN_PATH);//框架上级目录，用于下面替换路径防止暴露绝对地址
        krsort($trace); // 倒序调用顺序        
        $output = "<table><thead><tr><th>function</th><th>file</th></tr></thead><tbody>";
        foreach ($trace as $val) {
            $args = empty($val['args']) ? '' : "'" . implode("','", $val['args']) . "'";
            $args = str_replace($path, '...', $args);//过滤文件地址
            $code = $val['class'] . $val['type'] . $val['function'] . "($args)";
            $file = $val['file'];
            $line = $val['line'];
            $bug = '...' . DIRECTORY_SEPARATOR . basename($file) . ":" . $line;
            $output .= sprintf("<tr><td>%s</td><td>%s</td></tr>", $code, $bug);
        }
        $output .= '</tbody></table>';
        return $output;
    }
    
    /**
     * 设置异常处理类
     * @param unknown $config
     */
    public static function init($config = []){
        self::$config = $config;
    }
}
